//
//  YWAliyunOSSManager.m
//  maintain
//
//  Created by 郑想 on 15/10/30.
//  Copyright © 2015年 ewin. All rights reserved.
//

#import "YWAliyunOSSManager.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWMacro.h"
#import <AliyunOSSiOS/OSSService.h>

@interface YWAliyunOSSManager ()
@property (nonatomic, strong) OSSClient* ossClient;
@end

@implementation YWAliyunOSSManager

YWSingletonM(Manager)

    - (OSSClient*)ossClient
{
    if (!_ossClient) {
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:kAliyunAccessKey secretKey:kAliyunSecretKey];

        OSSClientConfiguration* conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3;
        conf.enableBackgroundTransmitService = NO;
        conf.timeoutIntervalForRequest = 15;
        conf.timeoutIntervalForResource = 24 * 60 * 60;

        self.ossClient = [[OSSClient alloc] initWithEndpoint:kAliyunEndPoint credentialProvider:credential clientConfiguration:conf];
    }
    return _ossClient;
}

- (NSString*)ossSaveFilePath:(NSString*)fileName
{
    return [NSString stringWithFormat:@"img/mission/%@/%@", [YWCommonTool shortDatePath], fileName];
}

- (NSString*)ossSaveAvatarFilePath:(NSString*)fileName
{
    return [NSString stringWithFormat:@"img/avatar/%@", fileName];
}

// 同步上传
- (BOOL)uploadPictureSyncWithFilePath:(NSString*)filePath isAvatar:(BOOL)isAvatar
{
    OSSPutObjectRequest* put = [OSSPutObjectRequest new];
    put.bucketName = kAliyunbucketName;
    put.objectKey = isAvatar ? [self ossSaveAvatarFilePath:[filePath lastPathComponent]] : [self ossSaveFilePath:[filePath lastPathComponent]];
    put.uploadingFileURL = [NSURL fileURLWithPath:filePath];

    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        //  YWLog(@"file %@: %lld, %lld, %lld", filePath, bytesSent, totalByteSent, totalBytesExpectedToSend);
    };

    OSSTask* putTask = [self.ossClient putObject:put];
    [putTask waitUntilFinished];
    if (!putTask.error) {
        return YES;
    }
    else {
        YWLog(@"upload object failed, error: %@", putTask.error);
        return NO;
    }
}

- (void)downloadFile:(NSString*)objectKey completeBlock:(void(^)(NSData* data))completeBlock
{
    OSSGetObjectRequest* request = [OSSGetObjectRequest new];
    // 必填字段
    request.bucketName = kAliyunbucketName;
    request.objectKey = objectKey;

    // 可选字段
    //    request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
    //        // 当前下载段长度、当前已经下载总长度、一共需要下载的总长度
    //        YWLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
    //    };
    // request.range = [[OSSRange alloc] initWithStart:0 withEnd:99]; // bytes=0-99，指定范围下载
    // request.downloadToFileURL = [NSURL fileURLWithPath:@"<filepath>"]; // 如果需要直接下载到文件，需要指明目标文件地址

    OSSTask* getTask = [self.ossClient getObject:request];

    [getTask continueWithBlock:^id(OSSTask* task) {
        if (!task.error) {
            //YWLog(@"download object success!");
            OSSGetObjectResult* getResult = task.result;
            if (completeBlock) {
                completeBlock(getResult.downloadedData);
            }
            //YWLog(@"download result: %@", );
        }
        else {
            if (completeBlock) {
                completeBlock(nil);
            }
           // YWLog(@"download object failed, error: %@", task.error);
        }
        return nil;
    }];
}
-(void)downloadFile:(NSString *)objectKey toFilePath:(NSString *)path progressBlock:(void (^)(float))progressBlock completeBlock:(void (^)(BOOL))completeBlock{
    OSSGetObjectRequest* request = [OSSGetObjectRequest new];
    // 必填字段
    request.bucketName = kAliyunbucketName;
    request.objectKey = objectKey;
    // 可选字段
    if (progressBlock) {
        request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
            progressBlock(totalBytesWritten*1.0/totalBytesExpectedToWrite);
            // 当前下载段长度、当前已经下载总长度、一共需要下载的总长度
//            YWLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
        };
    }
//     request.range = [[OSSRange alloc] initWithStart:0 withEnd:99]; // bytes=0-99，指定范围下载
     request.downloadToFileURL = [NSURL fileURLWithPath:path]; // 如果需要直接下载到文件，需要指明目标文件地址
    
    OSSTask* getTask = [self.ossClient getObject:request];
    
    [getTask continueWithBlock:^id(OSSTask* task) {
        if (!task.error) {
            //YWLog(@"download object success!");
//            OSSGetObjectResult* getResult = task.result;
            if (completeBlock) {
                completeBlock(YES);
            }
            //YWLog(@"download result: %@", );
        }
        else {
            if (completeBlock) {
                completeBlock(NO);
            }
            // YWLog(@"download object failed, error: %@", task.error);
        }
        return nil;
    }];
}
-(void)cancelTaskWithRequest:(OSSGetObjectRequest*)OSSGetObjectRequest{
//    [self.ossClient];
    [OSSGetObjectRequest cancel];
}
@end
